<?php 
// +----------------------------  页面元素相关控制器 ------------------------------------------
namespace app\controller;

use app\BaseController;
use app\dto\R;
use app\model\PageElements;
use think\facade\Db;

class PageElementControler extends BaseController{

    // 获取首页轮播图 show_position = index_slideshow
    public function getIndexSlideshow(){
        $data = PageElements::where('show_position', 'index_slideshow')->select();
        return json(R::result(1, '获取成功', $data));
    }

    // 获取分类 show_position = classify
    public function getClassify()
    {
        // 使用SQL自关联查询查询子父关系数据
        $parentData = Db::table('page_elements')
            ->where('show_position', 'classify')
            ->where('parent_id', null)  // 查询父分类
            ->select()
            ->toArray();
            
        $result = []; // 初始化结果数组
        
        foreach ($parentData as $parent) {
            // 查询每个父分类下的子分类
            $children = Db::table('page_elements')
                ->where('parent_id', $parent['ele_id'])
                ->select()
                ->toArray();
                
            $childElements = []; // 初始化子分类数组
            foreach ($children as $child) {
                $childElements[] = [
                    'itemName' => $child['item_name'],
                    'picture' => $child['picture']
                ];
            }
            
            // 构建返回的数据结构
            $result[] = [
                'showPosition' => $parent['show_position'],
                'itemName' => $parent['item_name'],
                'picture' => $parent['picture'],
                'chidrens' => $childElements
            ];
        }

        return json(R::result(1, '获取成功', $result));
    }
}
